import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { routerlist } from "../api/testapi/getRouterList";
import { useRouter } from "vue-router";
export const useTabStore = defineStore("tablist", () => {
  const router = useRouter();
  const routerList = reactive(routerlist[0].children);
  const getRouterList = () => {};

  const tabList = reactive(new Set());

  //删除某个项目
  //如果该项目在中间，游标不需要改变
  //如果改线木在最后面，游标需要向前走
  //如果长度小于1 那就仅剩一个首页 直接跳到首页
  const closeItem = (item) => {
    let tabListArr = [...tabList];
    //拿到item的下标
    let index = tabListArr.indexOf(item);
    console.log(index, tabListArr.length - 1);
    //点击关闭的路由不是所在路由那么就不需要发生跳转
    const currentPath = router.currentRoute.value.path;
    //如果下标是最后一个
    if (index == tabListArr.length - 1) {
      //当前路由不是最后一个路由
      if (currentPath == item.path) {
        router.replace(tabListArr[index - 1]);
      } else {
        tabList.delete(item);
        return;
      }
    } else {
      //游标 路由直接跳
      if (currentPath == item.path) {
        router.replace(tabListArr[index + 1]);
      } else {
        tabList.delete(item);
        return;
      }
    }
    tabList.delete(item);
  };

  const initRouter = () => {
    tabList.add(routerList[0]);
  };
  initRouter();
  const addRoute = (item) => {
    router.push(item);
    tabList.add(item);
  };
  return {
    addRoute,
    tabList,
    closeItem,
  };
});
